package  com.zhb.cloud.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: FileUtils
 * @author: zhb1316783262@163.com
 * @date: 2019年2月21日 下午9:36:36
 * @Description: 文件工具类
 */
public class FileUtils {
	public static void writeToFile(String path, String key) {
		// 1.指定要写到的文件目录及名称
		File file = new File(path);
		// 2.创建文件读入流对象
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 3.创建缓冲流对象加强fos功能
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		try {
			// 4.向流中写入数据
			bos.write(key.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 5.刷新和关闭流
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 输出指定文件的byte数组
	 * 
	 * @param filename 文件
	 * @return
	 */
	public static void writeBytes(String filePath, OutputStream os) throws IOException {
		FileInputStream fis = null;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				throw new FileNotFoundException(filePath);
			}
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int length;
			while ((length = fis.read(b)) > 0) {
				os.write(b, 0, length);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath 文件
	 * @return
	 */
	public static boolean deleteFile(String filePath) {
		boolean flag = false;
		File file = new File(filePath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	/**
	 * 读取图片地址 输出到页面
	 * 
	 * @param request
	 * @param response
	 * @param fileurl
	 * @throws IOException
	 */
	public static void readIMGTohtml(HttpServletRequest request, HttpServletResponse response, String fileurl)
			throws IOException {
		// 读取本地图片输入流
		FileInputStream inputStream = new FileInputStream(fileurl);
		int i = inputStream.available();
		// byte数组用于存放图片字节数据
		byte[] buff = new byte[i];
		inputStream.read(buff);
		// 记得关闭输入流
		inputStream.close();
		// 设置发送到客户端的响应内容类型
		response.setContentType("image/*");
		OutputStream out = response.getOutputStream();
		out.write(buff);
		// 关闭响应输出流
		out.close();
	}

}
